$(function () {
    init_cart();
    to_pay();
    to_delete();
});

function init_cart() {
    var count = 0;
    $.ajax({
        url: '/get-user-cart',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if (data.status) {
                var result_list = new Array(data.result);
                result_list.forEach((val, _idx, _arr) => {
                    val.forEach((sub_val, _sub_idx, _sub_arr) => {
                        $t_body = `
                            <tr>
                                <td class="align-middle">${sub_val['product_name']}</td>
                                <td class="align-middle">${sub_val['price']}</td>
                                <td class="align-middle">${sub_val['num']}</td>
                                <td class="align-middle"><button class="btn btn-sm btn-primary btn-close" uid="${sub_val['id']}">删除</button></td>
                            </tr>
                        `;
                        $('#table-body').append($t_body);
                        count += parseInt(sub_val['price']) * parseInt(sub_val['num']);
                    });
                });
                to_delete();
            } else {    
                alert('数据获取失败');
            }
            $('#total-price').text(count);
        }
    });
}

function to_pay() {
    $('#pay-confirm').click(() => {
        $('#pay-confirm').text('完善相关信息');
        $('#pay-confirm').attr('class', 'btn btn-block btn-success my-3 py-3');
        setTimeout("window.location.href='/page/payment-confirm.html';", 1000);
    });
}

function to_delete() {
    $('.btn-close').click(function () {
        $.ajax({
            url: `/delete-from-cart?id=${$(this).attr('uid')}`,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                if (data.status) {
                    location.reload();
                } else {
                    alert('数据删除失败');
                }
            }
        })
    });
}